/*
 * File Name：SpeechTextView.java
 * Copyright：Copyright 2008-2015 CiWong.Inc. All Rights Reserved.
 * Description： SpeechTextView.java
 * Modify By：res-jxliu
 * Modify Date：2015-1-16
 * Modify Type：Add
 */
package com.ciwong.epaper.widget.evaluate;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.modules.evaluate.bean.Sentence;
import com.ciwong.epaper.modules.evaluate.bean.WordDetail;
import com.ciwong.epaper.modules.evaluate.util.SpeechUtils;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.libs.utils.DeviceUtils;

import java.util.List;

/**
 * 显示分数的textView
 *
 * @author res-jxliu
 * @version ciwong v.1.0 2015-1-16
 * @since ciwong v.1.0
 */
public class SpeechTextView extends android.support.v7.widget.AppCompatTextView {
    private static final String TAG = "SpeechTextView";
    private Sentence mSentence;

    private int scoreColor;

    private float scoreTextSize;
    /**
     * 是否是听说填空
     */
    private boolean isFillblank;

    //评分条显示状态,弹出与收缩匹对
    private static boolean mAnimOut = false;


    public SpeechTextView(Context context) {
        super(context);
        init();
    }

    public void setScoreTextSize(float scoreTextSize) {
        this.scoreTextSize = scoreTextSize;
    }

    public SpeechTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
        init();
    }

    public SpeechTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs);
        init();
    }

    private void init(AttributeSet attrs) {
        TypedArray a = getContext().obtainStyledAttributes(attrs,
                R.styleable.speech_text_view);
        scoreTextSize = a.getDimensionPixelSize(
                R.styleable.speech_text_view_score_text_size, 30);
        a.recycle();

    }

    private void init() {
        final Resources mResources = getContext().getResources();
        DisplayMetrics metrics = DeviceUtils.getDisPlayMetrics();
        setWillNotDraw(false);
        if (scoreTextSize == 0) {
            scoreTextSize = TypedValue
                    .applyDimension(TypedValue.COMPLEX_UNIT_PX,
                            mResources.getDimensionPixelSize(
                                    R.dimen.speech_text_view_score_text_size),
                            metrics);
        }
    }

    /**
     * 是否是听说填空
     *
     * @param fillblank 是否是听说填空
     */
    public void setFillblank(boolean fillblank) {
        this.isFillblank = fillblank;
        if (mSentence != null) {
            setSentence(mSentence, true);
        }
    }

    /**
     * 设置分数显示颜色
     *
     * @param color 分数显示颜色
     */
    public void setScoreColor(int color) {
        scoreColor = color;
    }

    /**
     * 返回句子
     *
     * @return
     */
    public Sentence getSentence() {
        return mSentence;
    }

    public void setSentence(Sentence sentence) {
        setSentence(sentence, null, false, 0, true);
    }

    public void setSentence(Sentence sentence, boolean isShowScore) {
        setSentence(sentence, null, false, 0, isShowScore);
    }

    public void setSentence(Sentence sentence, TextView scoreView) {
        setSentence(sentence, scoreView, false, 0, true);
    }

    public void setSentence(Sentence sentence, TextView scoreView, boolean isShowScore) {
        setSentence(sentence, scoreView, false, 0, isShowScore);
    }

    /**
     * 设置段落
     *
     * @param sentence      {@link Sentence}
     * @param scoreView     单词时分数显示view
     * @param isFromPlayAll 是否来自播放全文
     * @param playAllColor  播放全文时句子颜色
     * @param isShwoScore   是否显示分数
     */
    public void setSentence(Sentence sentence, TextView scoreView,
                            boolean isFromPlayAll, int playAllColor, boolean isShwoScore) {
        try {
            mSentence = sentence;
            boolean isHasAnser = false;
            if (!TextUtils.isEmpty(mSentence.getAnswer())) {
                isHasAnser = true;
            }
            String text = "";
            if (!isFillblank || mSentence.hasGrade()) {
                if (mSentence.hasGrade()) {
                    //有答案
                    text = mSentence.getText();
                } else {
                    //显示
                    text = isHasAnser ? mSentence.getAnswer() : mSentence.getText();
                }
            } else {
                //没有答案
                String wordText = isHasAnser ? mSentence.getAnswer() : mSentence.getText();
                text = wordText;
                int[] indexArray = SpeechUtils.isMatchPersonName(text);
                if (text.startsWith("{") && text.contains("}")
                        && indexArray != null) {// 显示人名
                    text = text.substring(indexArray[0], indexArray[1] + 1);
                } else {// 显示首个单词
                    text = mSentence.getWordDetails().get(0).getText();
                }
                int len = wordText.length() - text.length();
                for (int i = 0; i < len; i++) {
                    if (i == 0) {
                        text += " ";
                        continue;
                    }
                    text += "_";
                }
            }

            SpannableStringBuilder style = new SpannableStringBuilder(text);
            List<WordDetail> words = mSentence.getWordDetails();
            int lastSpaceIndex = text.lastIndexOf(" ");
            int textLen = text.length();
            int offset = 0;
            int index;
            if (words != null && !words.isEmpty()) {
                int len = words.size();
                String itemText = text;
                for (int i = 0; i < len; i++) {
                    final WordDetail w = words.get(i);
                    index = (i != 0 && isFillblank ? -1 : 0);
                    ForegroundColorSpan span = new ForegroundColorSpan(
                            isFromPlayAll ? playAllColor : w.getColor());
                    int start = offset + itemText.indexOf(w.getText())
                            + (i != 0 ? index : 0);
                    start = start < 0 ? 0 : start;
                    int end = start + w.getText().length() - index;
                    end = end < 0 ? 0 : end;
                    style.setSpan(span, start, end,
                            Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                    itemText = text.substring(end);
                    offset = end;
                }
            }
            if (sentence.hasGrade() && !isFromPlayAll) {
                int bg;
                if (sentence.getScore() == SpeechUtils.SCORE_5) {
                    scoreColor = R.color.me_item_name_sub_txt_color;
                } else if (sentence.getScore() < SpeechUtils.SCORE_2) {
                    scoreColor = R.color.score_red;
                    bg = R.mipmap.score_red_rep;
                } else if (sentence.getScore() < SpeechUtils.SCORE_4) {
                    scoreColor = R.color.score_yellow;
                    bg = R.mipmap.score_orange_rep;
                } else {
                    scoreColor = R.color.score_green_word;
                    bg = R.mipmap.score_green_rep;
                }
            } else if (scoreView != null && mAnimOut) {
            }

            int[] indexArray = SpeechUtils.isMatchPersonName(style.toString());
            while (indexArray != null) {
                if (sentence.hasGrade() && !isFromPlayAll) {
                    // 将人名设置为黑色
                    ForegroundColorSpan span = new ForegroundColorSpan(
                            getResources().getColor(R.color.default_text_color));
                    style.setSpan(span, indexArray[0], indexArray[1],
                            Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                }
                // 将大括号剔除
                style = style.replace(indexArray[0], indexArray[0] + 1, "")
                        .replace(indexArray[1] - 1, indexArray[1], "");
                indexArray = SpeechUtils.isMatchPersonName(style.toString());
            }
            setText(style);
        } catch (Exception e) {
            e.getStackTrace();
            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_WORD_SPEECH, e.getMessage(), "SpeechTextView异常");

        }

    }

}
